 //
//  LYPhotoTools.m
//  MyTableView
//
//  Created by GaoLi on 15/12/11.
//  Copyright (c) 2015年 my. All rights reserved.
//

#import "LYPhotoTools.h"
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
@interface LYPhotoTools()
@property (nonatomic, strong) ALAssetsLibrary *library;

@end
@implementation LYPhotoTools

- (void)getImages
{
    NSMutableArray *urlArr = [[NSMutableArray alloc] init];
    NSMutableArray *imageArr = [[NSMutableArray alloc] init];
    
    ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror) {
        NSLog(@"相册访问失败 =%@", [myerror localizedDescription]);
        if ([myerror.localizedDescription rangeOfString:@"Global denied access"].location!=NSNotFound)
        {
            NSLog(@"无法访问相册.请在'设置->定位服务'设置为打开状态.");
        } else {
            NSLog(@"相册访问失败.");
        }
    };
    
    ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result,NSUInteger index, BOOL *stop) {
        if (result!=NULL)
        {
            if ([[result valueForProperty:ALAssetPropertyType]isEqualToString:ALAssetTypePhoto])
            {
                // 图片的路径
                [urlArr addObject:result.defaultRepresentation.url];
                // 图片对象(缩略图) result.thumbnail
                // 图片对象(全图)
                CGImageRef imageRef = result.defaultRepresentation.fullResolutionImage;
                UIImage *originImage =  [UIImage imageWithCGImage:imageRef];
                UIImage *image = [self imageByScalingAndCroppingForSize:CGSizeMake(40, 40) withImage:originImage];
                if (image!=nil) {
                    NSLog(@"%@   %d",image, index);
                    [imageArr addObject:[UIImage imageWithCGImage:result.defaultRepresentation.fullScreenImage]];
                }
                
            }
        }
    };
    
    ALAssetsLibraryGroupsEnumerationResultsBlock
    libraryGroupsEnumeration = ^(ALAssetsGroup* group,BOOL* stop){
        if (group != nil)
        {
            [group enumerateAssetsUsingBlock:groupEnumerAtion];
            if ([self.delegate respondsToSelector:@selector(photoToolsImages:urls:)])
            {
                [self.delegate photoToolsImages:imageArr urls:urlArr];
            }
        }
    };
    
    ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
    [library enumerateGroupsWithTypes:ALAssetsGroupAll
                           usingBlock:libraryGroupsEnumeration
                         failureBlock:failureblock];
}

//图片压缩到指定大小
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withImage:(UIImage *)newImage
{
    UIImage *sourceImage = newImage;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)getAlbumPicture:(void (^)(NSArray *array))AssetGroupBlock{
    // Load Albums into assetGroups
    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
    self.library = assetLibrary;
    dispatch_async(dispatch_get_main_queue(), ^
                   {
                       @autoreleasepool {
                           
                           // Group enumerator Block
                           NSMutableArray *assetGroups = [NSMutableArray array];
                           void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
                           {
                               if (group == nil) {
                                   return;
                               }
                               
                               // added fix for camera albums order
                               NSString *sGroupPropertyName = (NSString *)[group valueForProperty:ALAssetsGroupPropertyName];
                               NSUInteger nType = [[group valueForProperty:ALAssetsGroupPropertyType] intValue];
                               
                               if ([[sGroupPropertyName lowercaseString] isEqualToString:@"camera roll"] && nType == ALAssetsGroupSavedPhotos) {
                                   [assetGroups insertObject:group atIndex:0];
                               }
                               else {
                                   [assetGroups addObject:group];
                               }
                               dispatch_barrier_async(dispatch_get_main_queue(), ^{
                                   AssetGroupBlock(assetGroups);

                               });
                               // Reload albums
                           };
                           
                           // Group Enumerator Failure Block
                           void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
                               
                               if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusDenied) {
                                   NSString *errorMessage = @"您未对相册授权，请在设置中打开权限设置。";
                                   [[[UIAlertView alloc] initWithTitle:@"鉴权失败" message:errorMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];

                               } else {
                                   NSString *errorMessage = [NSString stringWithFormat:@"相册错误: %@ - %@", [error localizedDescription], [error localizedRecoverySuggestion]];
                                   [[[UIAlertView alloc] initWithTitle:@"错误" message:errorMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
                                   
                               }
                               
                               //                NSLog(@"A problem occured %@", [error description]);
                           };
                           
                           // Enumerate Albums
                           [self.library enumerateGroupsWithTypes:ALAssetsGroupAll
                                                       usingBlock:assetGroupEnumerator 
                                                     failureBlock:assetGroupEnumberatorFailure];
                           
                       }
                   });
}
@end
